package com.tianji.learning.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @param
 * @return
 */
@Slf4j
@Data
public class DelayTask<D> implements Delayed {

    private Long deadTaskNanos;
    private D data;

    //用户只需要传入一个时间就可以了
    public DelayTask(Duration duration, D data) {
        //我们计算用户传入的时间+系统当前时间
        this.deadTaskNanos = System.nanoTime() + duration.toNanos();
        this.data = data;
    }

    /**
     * 指定延时任务距离当前还有多久执行
     *
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        //距延迟任务时间执行还有多久，选最大的
        return unit.convert(Math.max(deadTaskNanos - System.nanoTime(), 0), TimeUnit.NANOSECONDS);
    }

    /**
     * 对延时任务进行排序.
     *
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        long diff = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if (diff > 0) {
            return 1;
        } else if (diff == 0) {
            return 0;
        }
        return -1;
    }
}
